package com.sportmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sportmall.common.Const;
import com.sportmall.common.ServerResponse;
import com.sportmall.common.TokenCache;
import com.sportmall.dao.UserMapper;
import com.sportmall.pojo.User;
import com.sportmall.service.IUserService;
import com.sportmall.util.MD5Util;
import com.sportmall.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.org.mozilla.javascript.internal.Token;

import java.util.Map;
import java.util.UUID;

@Service("iUserService")
public class UserServiceImlp implements IUserService {
    @Autowired
    private UserMapper userMapper;

    //region 前台

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public ServerResponse<UserVo> userLogin(String username, String password) {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return ServerResponse.createByErrorMessage("参数错误");
        }

        User user = userMapper.selectByUserName(username);
        if (user == null) {
            return ServerResponse.createByErrorMessage("用户不存在");
        }

        String md5PassWord = MD5Util.encode(password);
        if (user.getPassword().equals(md5PassWord)) {
            UserVo userVo = assembleUser(user);
            return ServerResponse.createBySuccess(userVo);
        }

        return ServerResponse.createByError();
    }

    /**
     * 注册用户
     * @param user
     * @return
     */
    @Override
    public ServerResponse userRegister(User user) {
        if (user == null)
            return ServerResponse.createByError();
        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())){
            return ServerResponse.createByErrorMessage("用户名和密码不能为空");
        }

        boolean b = userExist(user.getUsername());
        if (b)
            return ServerResponse.createByErrorMessage("用户已存在");

        User dbUser = new User();
        dbUser.setUsername(user.getUsername());
        dbUser.setPassword(MD5Util.encode(user.getPassword()));
        dbUser.setEmail(user.getEmail());
        dbUser.setPhone(user.getPhone());
        dbUser.setQuestion(user.getQuestion());
        dbUser.setAnswer(user.getAnswer());
        dbUser.setRole(Const.Role.ROLE_CUSTOMER);
        int row = userMapper.insert(dbUser);
        if (row > 0){
            return ServerResponse.createBySuccess("注册成功", assembleUser(dbUser));
        }
        return ServerResponse.createByErrorMessage("注册失败");
    }

    /**
     * 查询用户信息
     * @param userId
     * @return
     */
    @Override
    public ServerResponse selectUserInfo(Integer userId){
        if (userId == null){
            return ServerResponse.createByError();
        }

        User user = userMapper.selectByPrimaryKey(userId);
        if (user != null){
            return ServerResponse.createBySuccess(assembleUser(user));
        }
        return ServerResponse.createByError();
    }

    /**
     * 修改用户信息
     * @param userId
     * @param user
     * @return
     */
    @Override
    public ServerResponse updateUser(Integer userId, User user){
        if (userId == null || user == null || userId != user.getId()){
            return ServerResponse.createByErrorMessage("请检查参数");
        }

        User dbUser = userMapper.selectByPrimaryKey(userId);
        if (dbUser == null){
            return ServerResponse.createByErrorMessage("用户不存在");
        }

        User newUser = new User();
        newUser.setId(userId);
        newUser.setEmail(user.getEmail());
        newUser.setPhone(user.getPhone());
        newUser.setQuestion(user.getQuestion());
        newUser.setAnswer(user.getAnswer());
        int row = userMapper.updateByPrimaryKeySelective(newUser);
        if (row > 0){
            return ServerResponse.createBySuccess("更新成功", assembleUser(newUser));
        }

        return ServerResponse.createByError();
    }

    /**
     * 修改密码
     * @param userId
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @Override
    public ServerResponse resetPassword(Integer userId, String oldPassword, String newPassword){
        if (StringUtils.isBlank(oldPassword) || StringUtils.isBlank(newPassword)){
            return ServerResponse.createByErrorMessage("密码不能为空");
        }
        String md5OldPassword = MD5Util.encode(oldPassword);
        String md5NewPassword = MD5Util.encode(newPassword);

        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null){
            return ServerResponse.createByErrorMessage("用户不存在");
        }

        if (!user.getPassword().equals(md5OldPassword)){
            return ServerResponse.createByErrorMessage("旧密码不正确");
        }

        User dbUser = new User();
        dbUser.setId(userId);
        dbUser.setPassword(md5NewPassword);
        int row = userMapper.updateByPrimaryKeySelective(dbUser);
        if (row > 0){
            return ServerResponse.createBySuccessMessage("密码修改成功");
        }

        return ServerResponse.createByError();
    }

    /**
     * 检查用户名是否存在
     * @param username
     * @return
     */
    @Override
    public ServerResponse checkUserValid(String username){
        if (StringUtils.isBlank(username)){
            return ServerResponse.createByError();
        }

        boolean b = this.userExist(username);
        if (b){
            return ServerResponse.createBySuccessMessage("存在用户名");
        }else{
            return ServerResponse.createByErrorMessage("用户名不存在");
        }
    }

    /**
     * 找回密码-忘记密码
     * 查找用户设定的问题
     * @param username
     * @return
     */
    @Override
    public ServerResponse forgetSelectQuestion(String username){
        if (StringUtils.isBlank(username)){
            return ServerResponse.createByError();
        }
        User user = userMapper.selectByUserName(username);
        if (user == null){
            return ServerResponse.createByErrorMessage("用户不存在");
        }

        return ServerResponse.createBySuccess(user.getQuestion());
    }

    /**
     * 找回密码-验证答案
     * @param username
     * @param question
     * @param answer
     * @return
     */
    @Override
    public ServerResponse forgetCheckAnswer(String username, String question, String answer){
        if (StringUtils.isBlank(username) || StringUtils.isBlank(question) || StringUtils.isBlank(answer)){
            return ServerResponse.createByError();
        }
        User user = userMapper.selectByUserName(username);
        if (user == null){
            return ServerResponse.createByErrorMessage("用户不存在");
        }

        if (question.equals(user.getQuestion()) && answer.equals(user.getAnswer())){
            //生成token,并放入缓存
            String uuid = UUID.randomUUID().toString();
            TokenCache.setKey(username, uuid);

            Map<String, String> map = Maps.newHashMap();
            map.put("token", uuid);
            return ServerResponse.createBySuccess(map);
        }

        return ServerResponse.createByErrorMessage("答案不正确");
    }

    /**
     * 找回密码-修改密码
     * @param username
     * @param forgetToken
     * @param newPassword
     * @return
     */
    @Override
    public ServerResponse forgetResetPassword(String username, String forgetToken, String newPassword){
        if (StringUtils.isBlank(username) || StringUtils.isBlank(forgetToken) || StringUtils.isBlank(newPassword)){
            return ServerResponse.createByError();
        }

        User user = userMapper.selectByUserName(username);
        if (user == null) {
            return ServerResponse.createByErrorMessage("用户不存在");
        }

        String token = TokenCache.getKey(username);
        if (token == null || !forgetToken.equals(token)){
            return ServerResponse.createByErrorMessage("token不存在或者已经失效");
        }

        String md5NewPassword = MD5Util.encode(newPassword);

        User dbUser = new User();
        dbUser.setId(user.getId());
        dbUser.setPassword(md5NewPassword);
        int row = userMapper.updateByPrimaryKeySelective(dbUser);
        if (row > 0){
            return ServerResponse.createBySuccessMessage("修改密码成功");
        }
        return ServerResponse.createByErrorMessage("修改密码失败");
    }
    //endregion


    //region 内部函数

    /**
     * 装配UserVo
     *
     * @param user
     * @return
     */
    private UserVo assembleUser(User user) {
        if (user == null)
            return null;
        UserVo userVo = new UserVo();
        userVo.setId(user.getId());
        userVo.setUsername(user.getUsername());
        userVo.setEmail(user.getEmail());
        userVo.setPhone(user.getPhone());

        return userVo;
    }

    /**
     * 检查用户名是否存在
     * @param username
     * @return 存在返回true,不存在返回false
     */
    private boolean userExist(String username) {
        User user = userMapper.selectByUserName(username);
        return user != null ? true : false;
    }
    //endregion
}
